package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.server.api.TaoHuaApi;
import com.tanhua.dubbo.server.pojo.Voice;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.DeliverVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.*;
import java.util.Date;

@Service
public class DeliverService {

    @Reference(version = "1.0.0")
    private TaoHuaApi taoHuaApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     *桃花传音-发送语音
     * @param file
     * @return
     */
    public String deliver(MultipartFile file) {

        User user = UserThreadLocal.get();
        Voice voice = new Voice();
        voice.setUserId(user.getId());

        UserInfo userInfo = userInfoService.queryUserInfoByUserId(user.getId());

        voice.setGender(userInfo.getSex().name().toLowerCase());

        //将文件存储到 sso
        try {
            //上传语音到DFS
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
                    StringUtils.substringAfter(file.getOriginalFilename(), "."), null);
            voice.setVoiceUrl(fdfsWebServer.getWebServerUrl() + "/" + storePath.getFullPath());

            return taoHuaApi.deliver(voice);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 桃花传音-接收语音
     * @return
     */
    public DeliverVo receive() {

        User user = UserThreadLocal.get();
        DeliverVo deliverVo = new DeliverVo();

        String redisKey = "TAOHUA_VOICE_"+user.getId();

        if (!redisTemplate.hasKey(redisKey)){
            //设置次日凌晨失效 每日次数 10

            //当前日期加一天
            LocalDate now = LocalDateTime.now().toLocalDate().plusDays(1);
            //失效时间点
            long endTime = Date.from(now.atStartOfDay(ZoneOffset.ofHours(8)).toInstant()).getTime();
            //当前时间的毫秒值
            long startTime = new Date().getTime();
            redisTemplate.opsForValue().set(redisKey,"10",Duration.ofMillis( endTime-startTime));
        }

        String value = redisTemplate.opsForValue().get(redisKey);

        if (Integer.parseInt(value)<= 0){
            //当天没有接收次数了
            return deliverVo;
        }

        UserInfo userInfo = userInfoService.queryUserInfoByUserId(user.getId());

        //接收异性语音
        String gender = userInfo.getSex().name().equalsIgnoreCase("man")?"women":"man";
        Voice voice = taoHuaApi.receive(gender);

        if (null == voice){
            return deliverVo;
        }

        UserInfo userInfo1 = userInfoService.queryUserInfoByUserId(voice.getUserId());

        deliverVo.setId(userInfo1.getId().intValue());
        deliverVo.setAge(userInfo1.getAge());
        deliverVo.setAvatar(userInfo1.getLogo());
        deliverVo.setGender(userInfo1.getSex().name().equalsIgnoreCase("man")?"man":"woman");
        deliverVo.setNickname(userInfo1.getNickName());

        deliverVo.setSoundUrl(voice.getVoiceUrl());
        //redis 记录的次数进行 -1 操作
        deliverVo.setRemainingTimes(redisTemplate.opsForValue().decrement(redisKey).intValue());
        return deliverVo;
    }
}
